const laypage = layui.laypage;
// 初始化表单
const form = layui.form;
const selectedCategories = new Set();

let allCategories

const urlPrefix = "http://localhost:8080/"

$(document).ready(function () {
    window.pageEvent.onSendAllCategories((event, param) => {
        allCategories = param

        const selector = $("#category-selector")
        allCategories.forEach((v, k, m) => {
            selector.append(`<option value="${k}">${v}</option>`)
        })
        // 重新渲染select组件
        form.render('select')

        // 初始查询第一页爬虫模板
        $.get(urlPrefix + "task/queryList", {
            page: 1,
            pageSize: 10,
        }, function (response) {
            if (response.code !== "200") {
                layer.msg(response.msg)
                return
            }
            const data = response.data
            laypage.render({
                elem: 'pagination',
                count: data.total, //数据总数
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
            });
            const resultList = $('#result-list')
            // 渲染分页数据
            for (let item of data.dataList) {
                let categoriesHTML = []
                if (item.categories != null) {
                    for (let categoryId of item.categories.split(",")) {
                        const id = parseInt(categoryId)
                        categoriesHTML.push(`<span class="tag c${id % 5}">${allCategories.get(categoryId)}</span>`)
                    }
                }
                categoriesHTML = categoriesHTML.join('');
                const url = new URL(item.urls.split(",")[0])
                const domain = `${url.protocol}//${url.host}`
                resultList.append(`
            <div class="crawler-item">
            <div class="crawler-info">
                <div class="crawler-title">
                    <span id="taskId">${item.taskId}</span>
                    <span style="margin: 0 8px;">-</span>
                    <span>${item.taskName}</span>
                </div>
                <div class="crawler-meta">
                    <span>更新时间：${item.updatedAt.slice(0, 20).replace("T", " ")}</span>
                    <span style="margin: 0 15px;">|</span>                   
                    <span>执行次数：${item.taskExecTimes}</span>
                    <span style="margin: 0 15px;">|</span>
                    ${categoriesHTML}   
                </div>
                <div class="crawler-url">
                    ${domain}
                </div>
            </div>
            <div class="action-buttons">
                <button type="button" class="layui-btn layui-btn-sm" id="btn-edit">编辑</button>
                <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" id="btn-del">删除</button>
            </div>
        </div>
            `)
            }
        }).fail(function (xhr, status, error) {
            layer.msg("分页查询爬虫模板失败：" + status + " " + error);
        })
    })

    // 监听类别选择
    form.on('select(category)', function (data) {
        const $select = $(data.elem);
        const value = data.value;

        if (!value) return;

        if (selectedCategories.size >= 3) {
            layer.msg('最多只能选择3个类别');
            resetSelect($select);
            return;
        }

        if (selectedCategories.has(value)) {
            layer.msg('该类别已经选择过了');
            resetSelect($select);
            return;
        }

        addCategoryTag(value, allCategories.get(value));
        resetSelect($select);
    });

    // 添加类别标签
    function addCategoryTag(value, text) {
        selectedCategories.add(value);

        const $tag = $('<div>', {
            class: 'category-tag',
            html: text + '<span class="close-btn" data-value="' + value + '">×</span>'
        });

        // 添加删除按钮事件
        $tag.find('.close-btn').on('click', function () {
            const tagValue = $(this).data('value');
            selectedCategories.delete(tagValue);
            $tag.fadeOut(200, function () {
                $(this).remove();
            });
        });

        $('#selectedCategories').append($tag);
        $tag.hide().fadeIn(200);
    }

    // 重置选择框
    function resetSelect($select) {
        $select.val('');
        form.render('select');
    }

    // 监听表单重置
    $('.layui-form').on('reset', function () {
        selectedCategories.clear();
        $('#selectedCategories').children().fadeOut(200, function () {
            $('#selectedCategories').empty();
        });
    });

    // 监听表单提交
    $('.layui-form').on('submit', function (e) {
        e.preventDefault();
        // 获取表单数据
        const formData = {
            keywords: $('input[name="keywords"]').val(),
            categories: Array.from(selectedCategories),
            sort: $('input[name="sort"]:checked').val()
        };

        // TODO: 这里添加表单提交的处理逻辑
        console.log('提交的数据：', formData);
    });

    $('#backBtn').on('click', function () {
        window.pageEvent.switchPage(0)
    })

    // 点击某一任务项的编辑按钮
    $('#result-list').on('click', '#btn-edit', function (e) {
        // 请求任务详情数据
        $.get(urlPrefix + "task/queryDetail", {
            taskId: $(this).parent().prev().find('#taskId').text()
        }, (response) => {
            if (response.code !== "200") {
                layer.msg("获取任务详情失败：" + response.msg)
                return
            }
            window.pageEvent.switchPage(1, {
                task: {
                    taskId: response.data.taskId,
                    taskName: response.data.taskName,
                    categoryList: response.data.categories == null ? [] : response.data.categories.split(","),
                    urlList: response.data.urls.split(","),
                    taskDefine: response.data.taskDefine,
                    taskDescription: response.data.taskDescription == null ? "" : response.data.taskDescription,
                },
                allCategories: allCategories
            })
        }).fail((xhr, status, error) => {
            layer.msg("获取任务详情失败：" + status + " " + error);
        })

    })

    // 点击某一任务项的删除按钮
    $('#result-list').on('click', '#btn-del', function () {
        const btn = $(this)
        const taskId = btn.parent().prev().find('#taskId').text()
        // 弹出确认框
        layer.confirm('删除任务将导致该任务的执行记录，数据均被删除，请谨慎选择', {
            icon: 3,
            title: '提示',
            btn: ['确定', '取消']
        }, function (index) {
            layer.close(index);

            // 用户点击了确定
            $.ajax({
                url: urlPrefix + `task/delete?taskId=${taskId}`,
                type: 'DELETE',
                success: function (response) {
                    if (response.code !== "200") {
                        layer.msg("任务删除失败：" + response.msg)
                        return
                    }
                    layer.msg("任务删除成功")
                    // 清除当前任务对应的UI
                    btn.parent().parent().remove()
                },
                error: function (xhr, status, error) {
                    layer.msg("任务删除失败：" + status + " " + error);
                }
            })
        }, function (index) {
            layer.close(index);
        })
    })
})